Ternary Search Algorithm

The Ternary Search Algorithm is an advanced searching technique that is used for finding the maximum or minimum value of a unimodal function or an element in a sorted array. It is similar to the binary search algorithm, but instead of dividing the search interval into two equal parts, ternary search divides it into three equal parts. This technique can be applied to both continuous and discrete functions, where the function demonstrates a unimodal property, meaning it has a single maximum or minimum value. In the ternary search algorithm, two midpoints are calculated during each iteration, which helps in narrowing down the search interval. The algorithm compares the values at both midpoints and decides which part of the interval to discard based on the results. If the value at the first midpoint is greater than the value at the second midpoint, the algorithm discards the leftmost third of the interval. Otherwise, it discards the rightmost third of the interval. This process is repeated until the desired maximum or minimum value is found, or the search interval becomes smaller than a predetermined threshold. Overall, the ternary search algorithm boasts an efficient logarithmic time complexity of O(log3 N), making it a powerful tool for solving optimization problems and searching in sorted data structures.
/*
 Petar 'PetarV' Velickovic
 Algorithm: Ternary Search
*/

#include <stdio.h>
#include <math.h>
#include <string.h>
#include <iostream>
#include <vector>
#include <list>
#include <string>
#include <algorithm>
#include <queue>
#include <stack>
#include <set>
#include <map>
#define EPS 1e-12
using namespace std;
typedef long long lld;

//Ternarna pretraga maksimuma/minimuma funkcije koja menja monotonost najviše jednom
//Slozenost: O(log n)

inline double f(double x)
{
    return x*x + x - 1;
}

inline double ter_search(double left, double right)
{
    if (right - left < EPS) return (left+right)/2.0;
    double leftThird = (2.0*left + right)/3.0;
    double rightThird = (left + 2.0*right)/3.0;
    if (f(leftThird) > f(rightThird)) return ter_search(leftThird, right);
    else return ter_search(left, rightThird);
}

int main()
{
    printf("%.6lf\n",ter_search(-5.0, 1.0));
    return 0;
}

LANGUAGE:

DARK MODE: